//
//  HJAppleAuthenticator.m
//  GoogleLoginICloud
//
//  Created by lx on 2024/1/5.
//

#import "AppleAuthenticator.h"

@interface HJAppleUser()

@property (nonatomic, strong) NSString *userID;
@property (nonatomic, strong, nullable) NSString *fullName;
@property (nonatomic, strong, nullable) NSString *email;
@property (nonatomic, strong) NSString *authorizationCode;
@property (nonatomic, strong) NSString *identityToken;
@property (nonatomic, strong) NSString *realUserStatus;


@end

@implementation HJAppleUser


@end

@interface HJAppleSignInResult()

@property (nonatomic, strong) NSString *authorizationCode;
@property (nonatomic, strong) HJAppleUser *user;


@end

@implementation HJAppleSignInResult


@end

@interface AppleAuthenticator()<ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding>

@property (nonatomic, weak) UIWindow *window;
@property (nonatomic, strong) HJAppleSignInResult *signInResult;

@end

@implementation AppleAuthenticator

 
- (void)signInWithWithWindow:(UIWindow *)window {
    self.window = window;
    [self start];
}

+ (void)getCredentialStateWithUserId:(NSString *)userId completion:(void (^)(ASAuthorizationAppleIDProviderCredentialState credentialState, NSError * _Nullable error))completion API_AVAILABLE(ios(13.0)) {
    
    if (userId) {
        
        ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init];
        [appleIDProvider getCredentialStateForUserID:userId
                                          completion:^(ASAuthorizationAppleIDProviderCredentialState credentialState, NSError * _Nullable error) {
            switch (credentialState) {
                case ASAuthorizationAppleIDProviderCredentialAuthorized:
                    NSLog(@"授权状态有效");
                    break;
                case ASAuthorizationAppleIDProviderCredentialRevoked:
                    NSLog(@"苹果账号登录的凭据已被移除，需解除绑定并重新引导用户使用苹果登录");
                    break;
                case ASAuthorizationAppleIDProviderCredentialNotFound:
                    NSLog(@"未登录授权，直接弹出登录页面，引导用户登录");
                    break;
                case ASAuthorizationAppleIDProviderCredentialTransferred:
                    NSLog(@"授权AppleID提供者凭据转移");
                    break;
            }
            completion(credentialState, error);
        }];
    }
}

- (instancetype)init {
    if (self = [super init]) {
        if (@available(iOS 13.0, *)) {
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleSignInWithAppleStateChanged:) name:ASAuthorizationAppleIDProviderCredentialRevokedNotification object:nil];
        }
    }
    return self;
}

- (void)start {
    
    if (@available(iOS 13.0, *)) {
        ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init];
        ASAuthorizationAppleIDRequest *request = [appleIDProvider createRequest];
        request.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];

        ASAuthorizationController *authorizationController = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[request]];
        authorizationController.delegate = self;
        authorizationController.presentationContextProvider = self;
        [authorizationController performRequests];
    } else {
     
    }
 
}


#pragma mark - ASAuthorizationControllerDelegate
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)) {
 
    ASAuthorizationAppleIDCredential * credential = authorization.credential;
    // 苹果用户唯一标识符，该值在同一个开发者账号下的所有 App 下是一样的，开发者可以用该唯一标识符与自己后台系统的账号体系绑定起来。
    NSString * userID = credential.user;
    // 苹果用户信息 如果授权过，可能无法再次获取该信息
    
    NSString *fullName = [NSPersonNameComponentsFormatter localizedStringFromPersonNameComponents:credential.fullName
                                                                                        style:NSPersonNameComponentsFormatterStyleDefault
                                                                                      options:0];
    NSString * email = credential.email;
    // 服务器验证需要使用的参数
    NSString * authorizationCode = [[NSString alloc] initWithData:credential.authorizationCode encoding:NSUTF8StringEncoding];
    NSString * identityToken = [[NSString alloc] initWithData:credential.identityToken encoding:NSUTF8StringEncoding];
    // 用于判断当前登录的苹果账号是否是一个真实用户，取值有：unsupported、unknown、likelyReal
    ASUserDetectionStatus realUserStatus = credential.realUserStatus;
    
    HJAppleUser *appleUser = [[HJAppleUser alloc] init];
    appleUser.userID = userID;
    appleUser.email = email;
    appleUser.fullName = fullName;
    appleUser.realUserStatus = [NSString stringWithFormat:@"%ld", realUserStatus];;
    appleUser.identityToken = identityToken;
    appleUser.authorizationCode = authorizationCode;
    
    HJAppleSignInResult *signInResult = [[HJAppleSignInResult alloc] init];
    signInResult.user = appleUser;
    self.signInResult = signInResult;

    if ([self.delegate respondsToSelector:@selector(appleAuthenticator:didCompleteWithResult:)]) {
        [self.delegate appleAuthenticator:self didCompleteWithResult:signInResult];
    }
}
 
// 授权失败
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error  API_AVAILABLE(ios(13.0)){
    
    if ([self.delegate respondsToSelector:@selector(appleAuthenticator:didCompleteWithError:)]) {
        [self.delegate appleAuthenticator:self didCompleteWithError:error];
    }
    
    NSString *errorMsg = nil;
    switch (error.code) {
        case ASAuthorizationErrorCanceled:
            errorMsg = @"用户取消了授权请求";
            break;
        case ASAuthorizationErrorFailed:
            errorMsg = @"授权请求失败";
            break;
        case ASAuthorizationErrorInvalidResponse:
            errorMsg = @"授权请求响应无效";
            break;
        case ASAuthorizationErrorNotHandled:
            errorMsg = @"未能处理授权请求";
            break;
        case ASAuthorizationErrorUnknown:
            errorMsg = @"授权请求失败未知原因";
            break;
    }

    NSLog(@"%@", errorMsg);
}

#pragma mark - ASAuthorizationControllerPresentationContextProviding
- (ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller  API_AVAILABLE(ios(13.0)){
    return self.window;
}

#pragma mark- apple授权状态 更改通知
- (void)handleSignInWithAppleStateChanged:(NSNotification *)notification {
    NSLog(@"%@", notification.userInfo);
    if ([self.delegate respondsToSelector:@selector(appleAuthenticator:appleIdStateChanged:)]) {
        [self.delegate appleAuthenticator:self appleIdStateChanged:notification.userInfo];
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
